package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
)


type KeyWord struct {
	Id         int
	Key_name    string
	Cn    string
	En     string
	Th     string
}

type KeyWordList struct {
	id         int
	key_name    string
	cn    string
	en     string
	th     string
}

type ParcelAddr struct {
	Id         int
	Pno    string
	Orig_addr    string
	Clean_addr     string
	Fle_city_code string
}

func (a *KeyWord) TableName() string {
	return TableName("key_word")
}
func (a *ParcelAddr) TableName() string {
	return TableName("parcel_addr")
}

func KeyWordGetList(page, pageSize int, filters ...interface{}) ([]*KeyWord, int64) {
	offset := (page - 1) * pageSize
	list := make([]*KeyWord, 0)
	query := orm.NewOrm().QueryTable(TableName("key_word"))
	if len(filters) > 0 {
		l := len(filters)
		for k := 0; k < l; k += 2 {
			query = query.Filter(filters[k].(string), filters[k+1])
		}
	}
	total, _ := query.Count()
	query.OrderBy("-id").Limit(pageSize, offset).All(&list)
	return list, total
}

func ListALl() ([]*KeyWord,int64) {
	var list []*KeyWord
	num, err := orm.NewOrm().QueryTable(TableName("key_word")).All(&list)
	if err != nil || num < 1 {
		fmt.Println("查询错误")
	}
	return list, num
}


func KeyWordGetListTwo(page, pageSize int, filters ...interface{}) ([]*KeyWord,int64) {
	offset := (page - 1) * pageSize
	//list := make([]*KeyWord, 0)
	var list []*KeyWord
	num, err := orm.NewOrm().Raw("SELECT * FROM "+ TableName("key_word")  +"  where id < ? limit ?,?", 500000,page,offset).QueryRows(&list)
	if err != nil || num < 1 {
		fmt.Println(list)
		fmt.Println("查询错误")
	}
	return list, num
}

func GetById(id int) (*KeyWord, error) {
	r := new(KeyWord)
	err := orm.NewOrm().QueryTable(TableName("key_word")).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}
	return r, nil
}

func Add(a *KeyWord) (int64, error) {
	return orm.NewOrm().Insert(a)
}

func (a *KeyWord) Update(fields ...string) error {
	if _, err := orm.NewOrm().Update(a, fields...); err != nil {
		return err
	}
	return nil
}

func GetByName(KeyName string) (*KeyWord, error) {
	a := new(KeyWord)
	err := orm.NewOrm().QueryTable(TableName("key_word")).Filter("key_name", KeyName).One(a)
	if err != nil {
		return nil, err
	}
	return a, nil
}


func ParcelAddrGetList(page, pageSize int, filters ...interface{}) ([]*ParcelAddr, int64) {
	offset := (page - 1) * pageSize
	list := make([]*ParcelAddr, 0)
	query := orm.NewOrm().QueryTable(TableName("parcel_addr"))
	if len(filters) > 0 {
		l := len(filters)
		for k := 0; k < l; k += 2 {
			query = query.Filter(filters[k].(string), filters[k+1])
		}
	}
	total, _ := query.Count()
	query.OrderBy("-id").Limit(pageSize, offset).All(&list)
	return list, total
}